import ChunkItem from './ChunkItem';
import '../../styles/maonry.scss';
import { memo, useMemo, useState } from 'react';
import datasetService from '@/api/services/datasetService';
import DeleteModal from '@/pages/components/modal/DeleteModal';
import { message } from 'antd';
import { useContextSelector } from 'use-context-selector';
import { CollectionContext } from '../../context';
import { CollectionEvent, DatasetDataListItemType } from '@/types/dataset';
import { useScrollPagination } from '@/hooks/use-pagination/useVirtualScrollPagination';
import { t } from '@/locales/i18n';
import DataEmpty from '@/components/empty/DataEmpty';
import NewChunkModal from './NewChunkModal';
import NotData from '@/components/NotData';
import { useDatasetStore } from '@/store/datasetStore';

interface Props {
  searchText?: string;
  collectionId: string;
}

const Chunks = ({ searchText, collectionId }: Props) => {
  const [delModalVisible, setDelModalVisible] = useState(false);
  const [editId, setEditId] = useState('');
  const { event$ } = useContextSelector(CollectionContext, (s) => s);
  const [newChunkModal, setNewChunkModal] = useState(false);
  const [currentEditItem, setCurrentEditItem] = useState<DatasetDataListItemType | undefined>(
    undefined,
  );
  const { datasetStatus } = useDatasetStore();

  const scrollParams = useMemo(
    () => ({
      collectionId,
      searchText,
    }),
    [collectionId, searchText],
  );

  const EmptyTipDom = useMemo(() => <DataEmpty iconSize={200}></DataEmpty>, [t]);

  const delData = async () => {
    try {
      const res = await datasetService.delDatasetData(editId);
      message.success('删除成功');
      setDelModalVisible(false);
      setDatasetDataList((prev) => {
        return prev.filter((data) => data._id !== editId);
      });
      setEditId('');
    } catch (error) {
      console.error(error);
    }
  };

  const onDelDataClick = (id: string) => {
    if (datasetStatus === 'upload_publish' || datasetStatus === 'delete_publish') {
      message.warning('请先通过审核');
      return;
    }

    setEditId(id);
    setDelModalVisible(true);
  };

  event$?.useSubscription((event) => {
    if (event === CollectionEvent.UPDATECOLLECTIONDATAS) {
      refreshList();
    }
  });

  const {
    data: datasetDataList,
    ScrollData,
    total,
    refreshList,
    setData: setDatasetDataList,
  } = useScrollPagination(datasetService.getCollectionDatas, {
    pageSize: 15,
    params: scrollParams,
    refreshDeps: [searchText, collectionId],
    EmptyTip: (
      <div className="flex h-full items-center justify-center">
        <NotData />
      </div>
    ),
    // EmptyTip: EmptyTipDom,
  });

  const onChunkItemClicked = (item: DatasetDataListItemType) => {
    setCurrentEditItem(item);
    setNewChunkModal(true);
  };

  const onChunkEditConfirm = async (q: string, a: string) => {
    try {
      if (!currentEditItem) {
        return;
      }
      await datasetService.updateCollectionData({
        ...currentEditItem,
        q: q,
        a: a,
        dataId: currentEditItem?._id,
      });
      setNewChunkModal(false);
      message.success('编辑成功');
      // refreshList();
      currentEditItem.a = a;
      currentEditItem.q = q;
    } catch (error) {}
  };

  return (
    <div className="flex h-full w-full flex-col">
      <ScrollData>
        <div className="masonry text-wrap">
          {datasetDataList.map((item) => {
            return (
              <div
                className="break-inside p-2"
                key={item._id}
                onClick={() => {
                  if (datasetStatus === 'upload_publish' || datasetStatus === 'delete_publish') {
                    return;
                  }
                  onChunkItemClicked(item);
                }}
              >
                <ChunkItem data={item} delData={onDelDataClick} />
              </div>
            );
          })}
        </div>
      </ScrollData>
      <DeleteModal
        open={delModalVisible}
        onOk={delData}
        onCancel={() => setDelModalVisible(false)}
      />
      <NewChunkModal
        onCancel={() => {
          setCurrentEditItem(undefined);
          setNewChunkModal(false);
        }}
        data={currentEditItem}
        open={newChunkModal}
        onConfirm={onChunkEditConfirm}
      />
    </div>
  );
};

export default memo(Chunks);
